const User = require('../models/User');

// 创建用户
exports.createUser = async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.json({ message: '用户创建成功', data: user });
  } catch (error) {
    res.status(500).json({ message: '用户创建失败', error: error.message });
  }
};

// 获取用户列表
exports.getUsers = async (req, res) => {
  try {
    const users = await User.find().populate('deptId roles');
    res.json({ message: '获取用户列表成功', data: users });
  } catch (error) {
    res.status(500).json({ message: '获取用户列表失败', error: error.message });
  }
};

// 分页获取用户列表
exports.getUserPage = async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const skip = (page - 1) * limit;

    const users = await User.find()
      .skip(skip)
      .limit(limit)
      .populate('deptId roles');

    const totalUsers = await User.countDocuments();

    res.json({
      message: '获取用户分页数据成功',
      data: {
        users,
        currentPage: page,
        totalPages: Math.ceil(totalUsers / limit),
        totalUsers
      }
    });
  } catch (error) {
    res.status(500).json({ message: '获取用户分页数据失败', error: error.message });
  }
};

// 根据 ID 获取用户
exports.getUserById = async (req, res) => {
  try {
    const user = await User.findById(req.params.id).populate('deptId roles');
    if (!user) {
      return res.status(404).json({ message: '用户未找到' });
    }
    res.json({ message: '获取用户信息成功', data: user });
  } catch (error) {
    res.status(500).json({ message: '获取用户信息失败', error: error.message });
  }
};

// 更新用户
exports.updateUser = async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!user) {
      return res.status(404).json({ message: '用户未找到' });
    }
    res.json({ message: '用户更新成功', data: user });
  } catch (error) {
    res.status(500).json({ message: '用户更新失败', error: error.message });
  }
};

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) {
      return res.status(404).json({ message: '用户未找到' });
    }
    res.json({ message: '用户删除成功' });
  } catch (error) {
    res.status(500).json({ message: '用户删除失败', error: error.message });
  }
};